<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="客户姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.customer_id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.real_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center" width="180">
        <template slot-scope="{row}">
          <span>{{ row.idcard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" width="120">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联医院" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.merchant_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联订单" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.order_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="累计还款" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.paid_money_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余还款" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.no_paid_money_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="逾期次数" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.over_money_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户资料备注" align="center" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.over_money_count }}</span>
        </template>
      </el-table-column>
      <!--  <el-table-column label="状态" class-name="status-col" width="120">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusFilter}}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!-- <el-button size="mini" type="warning" @click="showMerchantList(row.customer_id)">
            关联商户
          </el-button>
          <el-button size="mini" type="success" @click="jumpOrder(row.customer_id)">
            关联订单
          </el-button> -->

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="temp.real_name" type="text" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="temp.mobile" type="text" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="身份证" prop="idcard">
          <el-input v-model="temp.idcard" type="text" placeholder="请输入身份证号码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogMerchantVisible" title="关联商户">
      <el-table :data="merchantData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="merchant_name" label="商家名称">
          <template slot-scope="{row}">
            {{ row.merchant_name }}
          </template>
        </el-table-column>
        <el-table-column prop="merchant_id" label="操作">
          <template slot-scope="{row}">
            <el-button @click="jumpMerchant(row.merchant_id)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogMerchantVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  showMerchantList,
  showOrderList,
  updateCustomer,
  getCustomerList,
  getDesc
} from '@/api/customer'
import waves from '@/directive/waves' // waves directive
import {
  parseTime
} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'ComplexTable',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '禁用',
        1: '启用'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      desc_list: [],

      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        keyword: undefined

      },
      sortOptions: [{
        label: 'ID Ascending',
        key: 'sale_id asc'
      }, {
        label: 'ID Descending',
        key: 'sale_id desc'
      }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        real_name: '',
        idcard: '',
        mobile: '',
        status: '1'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogMerchantVisible: false,
      dialogOrderVisible: false,
      merchantData: [],
      orderData: [],
      rules: {
        real_name: [{
          required: true,
          message: '销售人员姓名必须输入',
          trigger: 'change'
        }],
        mobile: [{
          required: true,
          message: '手机号码必须输入',
          trigger: 'change'
        }],
        idcard: [{
          required: true,
          message: '身份证号码必须输入',
          trigger: 'blur'
        }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    // this.getDesc();
  },
  methods: {
    showMerchantList(customer_id) {
      this.dialogMerchantVisible = true
      showMerchantList(customer_id).then(resp => {
        this.merchantData = resp.data
      })
    },
    jumpOrder(customer_id) {
      this.$router.push('/order/index/' + customer_id)
    },
    jumpMerchant(merchant_id) {
      this.$router.push('/merchant/index/' + merchant_id)
    },
    getList() {
      this.listLoading = true
      getCustomerList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.2 * 1000)
      })
    },
    getDesc() {
      getDesc().then(response => {
        this.desc_list = response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        real_name: '',
        idcard: '',
        mobile: ''
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.password = ''
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateCustomer(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000,
              onclose: this.getList()
            })
          })
        }
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
